package com.social_network.test_twitter;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.conf.ConfigurationBuilder;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.sax.StartElementListener;
import android.util.Log;
import android.widget.Toast;

import com.social_network.test_twitter.TwitterObject.TwDialogListener;

public  class Twitter extends Observable implements SocialNetwork {

	
	private static final String default_consumer_key = "uyjqF6fEZ7YacQLfkrXdAg";
	private static final String default_secret_key = "81OD4ht0McXUn7vZfPlyFgeaxU3Vgarq1I1KQEnC4";
	
	////////////////////////////////////////////////////////////////////////
	
	
	
	private static String TAG_FOLLOWER = "follower";
	private static String TAG_FOLLOWING = "following";
	
	private static String API_getFollowing = "";
	private static String API_getFollower = "";
	private static String API_getInfoFriend ="";
	
	private static String IDs = "ids";
	
	private static String TAG_ID = "id";
	private static String TAG_NAME = "name";
	private static String TAG_LOCATION = "location";
	
	String UserName = "";
	
	private Context mcontext;
	
	private TwitterObject mTwitterObject ;
	
	private JSONObject FollowList = new JSONObject();
	JSONParser jsonParser =new JSONParser();
	private ProgressDialog pDialog;
	
	
	public Twitter(){
		
	}
	
	public Twitter(Observer observer){
		addObserver(observer);
	}
	
	
	
	 	 //=============================================================//
		// 					Log in									   //
	   //=============================================================//
	
	public boolean login(Context context, String username, String passwork) {
		mcontext = context;
		mTwitterObject = new TwitterObject(mcontext, default_consumer_key, default_secret_key);
		
		mTwitterObject.setListener(mTwDialogListener);
		
		if (mTwitterObject.hasAccessToken()) {
			UserName = getUserName();
			return true;
		} else {
			mTwitterObject.authorize();
			
		}	
		if (mTwitterObject.hasAccessToken())
		{ 
			UserName = getUserName();
			return true;
		}
		else 
		return false;
		
	}



	private String getUserName() {
		String Name="";
		if (mTwitterObject.hasAccessToken()) {
			Name	= mTwitterObject.getUsername();		
		}
		return (Name.equals("")) ? "No Name" : Name;
	}

	private final TwDialogListener mTwDialogListener = new TwDialogListener() {
		
		@Override
		public void onError(String value) {
			Toast.makeText(mcontext, "Twitter connection failed", Toast.LENGTH_LONG).show();
		}
		
		@Override
		public void onComplete(String value) {
				UserName = getUserName();
				Toast.makeText(mcontext, "Connected to Twitter as " + UserName, Toast.LENGTH_LONG).show();
				}
	};
	

	
	
		 //=============================================================//
		// 					Update status							   //
	   //=============================================================//
	public boolean post(String message, String link) {

			String mess = message+" "+link;
			
			 if (mess.trim().length() > 0) {
                 // update status
                 new updateTwitterStatus().execute(mess);
                 return true;
             } else {
                 // EditText is empty
                 Toast.makeText(mcontext,
                         "Please enter status message", Toast.LENGTH_SHORT)
                         .show();
                 return false;
             }
			
	}
	
	
	class updateTwitterStatus extends AsyncTask<String, String, String> {
		 
	    /**
	     * Before starting background thread Show Progress Dialog
	     * */
	    @Override
	    protected void onPreExecute() {
	        super.onPreExecute();
	        pDialog = new ProgressDialog(mcontext);
	        pDialog.setMessage("Updating to twitter...");
	        pDialog.setIndeterminate(false);
	        pDialog.setCancelable(false);
	        pDialog.show();
	    }
	 
	   
	    protected String doInBackground(String... args) {
	        Log.d("Tweet Text", "> " + args[0]);
	        String status = args[0];
	        try {
	        	
	        	// Access Token
	            String access_token = mTwitterObject.mAccessToken.getToken();
	            // Access Token Secret
	            String access_token_secret = mTwitterObject.mAccessToken.getTokenSecret();
	            
	            ConfigurationBuilder builder = new ConfigurationBuilder();
	            builder.setOAuthConsumerKey(default_consumer_key);
	            builder.setOAuthConsumerSecret(default_secret_key);
	            builder.setOAuthAccessToken(access_token);
	            builder.setOAuthAccessTokenSecret(access_token_secret);

	            Log.d("accessToken", access_token);
	            Log.d("AccessTokenSecret", access_token_secret);
	            
	            twitter4j.Twitter twitter = new TwitterFactory(builder.build()).getInstance();

	            // Update status
	            twitter4j.Status response = twitter.updateStatus(status);
	 
	            Log.d("Status", "> " + response.getText());
	            
	            
	        } catch (TwitterException e) {
	            // Error in updating status
	            Log.d("Twitter Update Error", e.getMessage());

	        }
	        return null;
	    }

	    protected void onPostExecute(String file_url) {
	    	pDialog.dismiss();
	    }
	 
	}
	
	 //=============================================================//
	// 					Log out									   //
   //=============================================================//
	
	public boolean LogOut(){

			mTwitterObject.resetAccessToken();
			mTwitterObject= null;
			
			return true;
	}
	
	
	  //==============================================================//
	 //				Get Followings									 //	
	//==============================================================//

	public void getFollowings(){
		
		API_getFollowing = "https://api.twitter.com/1/friends/ids.json?cursor=-1&user_id="+mTwitterObject.mAccessToken.getUserId();

		
		String params = TAG_FOLLOWING;
		
		new getFollowAsync().execute(params);

	}

	

		  //==============================================================//
		 //				Get Followers									 //	
		//==============================================================//
	
	
	public void getFollower(){
			
			API_getFollower= "https://api.twitter.com/1/followers/ids.json?cursor=-1&user_id="+mTwitterObject.mAccessToken.getUserId();
			Log.d("URL STRING", API_getFollower);
			String params = TAG_FOLLOWER;
			
			new getFollowAsync().execute(params);
			
			
	}
	
	//      status follower update
	// http://api.twitter.com/1/statuses/followers/17790274.json
	//http://api.twitter.com/1/statuses/followers/rohitfantasy.json
	
	
class getFollowAsync extends AsyncTask<String, String, String> {
	
    
	JSONArray arrID = null;
	
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(mcontext);
            pDialog.setMessage("Loading Friends list. Wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }
 

        protected String doInBackground(String... args) {
        	String type = args[0];

        	
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // getting JSON string from URL
            JSONObject json = null;
            if(type.equals(TAG_FOLLOWING))
            	json = jsonParser.makeHttpRequest(API_getFollowing, "GET", params);
            else
            	json = jsonParser.makeHttpRequest(API_getFollower, "GET", params);

            Log.d("JSON Text: ", json.toString());
 
            try {
            	JSONArray FriendsList = new JSONArray();

                    arrID = json.getJSONArray(IDs);
                    Log.d("ArrIDs : ", arrID.toString());
 
                    // looping throug
                    for (int i = 0; i < arrID.length(); i++) {
                        Long ID = arrID.getLong(i);
                        Log.d("id ", ""+ID);
                        
                        API_getInfoFriend = "https://api.twitter.com/1/users/show.json?user_id="+ID+"&include_entities=true";
                        
                        
                        JSONObject jsonInfo = jsonParser.makeHttpRequest(API_getInfoFriend, "GET", params);
                        Log.d("Json info ", jsonInfo.toString());
                        
                        String name = jsonInfo.getString(TAG_NAME);
                        String location = jsonInfo.getString(TAG_LOCATION);

                        
                        JSONObject Friend = new JSONObject();
                        
                        Friend.put(TAG_ID, ID);
                        Friend.put(TAG_NAME, name);
                        Friend.put(TAG_LOCATION, location);
                        
                        FriendsList.put(Friend);
                        Log.d("Friend list: ", FriendsList.toString());
                        
                    }
                    FollowList = new JSONObject();
                    
                    if(type.equals(TAG_FOLLOWING))
                    {
	                    FollowList.putOpt("Followings", FriendsList);
	                    Log.d("FollowList: ", FollowList.toString());
                    }
                    else 
                    {
                    	FollowList.putOpt("Followers", FriendsList);
                    	Log.d("FollowList: ", FollowList.toString());
                    }
	                   
            } catch (JSONException e) {
            }
 
            return null;
        }
 

        protected void onPostExecute(String file_url) {
            
            // updating UI from Background Thread
           // Toast.makeText(mcontext, "load success", Toast.LENGTH_SHORT).show(); 
        	pDialog.dismiss();
        	setChanged();
            notifyObservers(FollowList);
            setChanged();
        }
	
	}


  //==============================================================//
 //				Share SMS/Email									 //	
//==============================================================//

	


	
}
